//
//  QINPopUpTool.m
//  qkProject
//
//  Created by Q on 2022/12/12.
//  Copyright © 2022 XLkeji. All rights reserved.
//

#import "QINPopUpTool.h"
#import "SQFoundationSafeHeader.h"



@interface QINPopAlertBgView : UIView

@end

@implementation QINPopAlertBgView

@end

#pragma mark -- toast
@interface QINToolTipView : UIView
+(void)showMessage:(NSString *)message offset:(CGFloat)offset;

@end

@implementation QINToolTipView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    }
    return self;
}

+(void)showMessage:(NSString *)message offset:(CGFloat)offset
{
    UIWindow * window ;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 13.0){
        window = [[[UIApplication sharedApplication] windows] objectAtIndex:0] ;
    }else{
        window = [UIApplication sharedApplication].keyWindow;
    }
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor redColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 6;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    if (message.length>0) {
        UILabel *label = [[UILabel alloc]init];
        NSAttributedString *attributeStr = [[NSAttributedString alloc]initWithString:message attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
        CGRect rect = [attributeStr boundingRectWithSize:CGSizeMake(300, 9000) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
        label.frame = CGRectMake(10, 7, rect.size.width+2.0, rect.size.height);
        label.text = message;
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:15];
        label.numberOfLines = 0;
        [showview addSubview:label];
        
        showview.frame = CGRectMake((SCREEN_WIDTH - rect.size.width - 20)/2, SCREEN_HEIGHT/2.0+offset, rect.size.width+20, rect.size.height+15);
        [UIView animateWithDuration:1.5 animations:^{
            showview.alpha = 0.9;
        } completion:^(BOOL finished) {
            [showview removeFromSuperview];
        }];
    }
}

@end



#pragma mark - PopStyleModel
@interface PopStyleModel : NSObject

@property (nonatomic, assign) QINAlertPopUpStyle style;
@property (nonatomic, strong) UIView *popUpView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, assign) BOOL appearWhenLastDismiss;

@end

@implementation PopStyleModel


@end


#pragma mark - QINPopUpTool
#pragma mark - QINPopUpTool
#pragma mark - QINPopUpTool


@interface QINPopUpTool()<UIGestureRecognizerDelegate>
{
    NSTimer *timer;
}
@property (nonatomic, strong) NSMutableArray *maryStack;

@property (nonatomic, strong) NSMutableDictionary *storeViewMap;

@end

@implementation QINPopUpTool

+ (instancetype)sharedInstance {
    static QINPopUpTool *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

- (void)setBgColor:(UIColor *)bgColor {
    _bgColor = bgColor;
}

#pragma mark - Pop Up View function
- (void)popUpWithView:(UIView *)view withAnimation:(QINAlertPopUpStyle)animation withCanTapBgCancel:(BOOL)canTapBgCancel closeBefore:(BeforeAlertBehavior)closeBefore  {

    if (closeBefore == BeforeAlertBehaviorClose) {
        [self removePopUpView];
    } else if (closeBefore == BeforeAlertBehaviorHidden){
        [self hiddenCurrentPopUpView];
    }

    // 背景view
    QINPopAlertBgView *bgView = [[QINPopAlertBgView alloc] init];
    if (canTapBgCancel) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removePopUpViewWhenAppearOther)];
        tap.delegate = self;
        [bgView addGestureRecognizer:tap];
    }
    PopStyleModel *model = [[PopStyleModel alloc] init];
//    model.appearWhenLastDismiss = rAppear;
    model.style = animation;
    model.popUpView = bgView;
    model.contentView = view;
    [self.maryStack addObject:model];

    [[[[UIApplication sharedApplication] delegate] window] addSubview:bgView];
    bgView.backgroundColor = _bgColor ? _bgColor : [[UIColor blackColor] colorWithAlphaComponent:0.3];
    bgView.frame = [[[UIApplication sharedApplication] delegate] window].bounds;
    // 嵌入view
    [bgView addSubview:view];
    
    [self popUpWithModel:model];
}


- (void)popUpWithView:(UIView *)view withAnimation:(QINAlertPopUpStyle)animation withCanTapBgCancel:(BOOL)canTapBgCancel closeBefore:(BeforeAlertBehavior)closeBefore  bgColor:(UIColor *)bgColor  {

    if (closeBefore == BeforeAlertBehaviorClose) {
        [self removePopUpView];
    } else if (closeBefore == BeforeAlertBehaviorHidden){
        [self hiddenCurrentPopUpView];
    }

    // 背景view
    QINPopAlertBgView *bgView = [[QINPopAlertBgView alloc] init];
    if (canTapBgCancel) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removePopUpViewWhenAppearOther)];
        tap.delegate = self;
        [bgView addGestureRecognizer:tap];
    }
    PopStyleModel *model = [[PopStyleModel alloc] init];
    model.style = animation;
    model.popUpView = bgView;
    model.contentView = view;
    [self.maryStack addObject:model];

    [[[[UIApplication sharedApplication] delegate] window] addSubview:bgView];
    bgView.backgroundColor = bgColor;
    bgView.frame = [[[UIApplication sharedApplication] delegate] window].bounds;
    // 嵌入view
    [bgView addSubview:view];
    
    [self popUpWithModel:model];
}


- (void)popUpWithView:(UIView *)view withAnimation:(QINAlertPopUpStyle)animation closeBefore:(BeforeAlertBehavior)closeBefore {
    if (closeBefore == BeforeAlertBehaviorClose) {
        [self removePopUpView];
    } else if (closeBefore == BeforeAlertBehaviorHidden){
        [self hiddenCurrentPopUpView];
    }

    // 背景view
    QINPopAlertBgView *bgView = [[QINPopAlertBgView alloc] init];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenCurrentPopUpView)];
    tap.delegate = self;
    [bgView addGestureRecognizer:tap];
    
    PopStyleModel *model = [[PopStyleModel alloc] init];
    model.style = animation;
    model.popUpView = bgView;
    model.contentView = view;
    [self.maryStack addObject:model];

    [[[[UIApplication sharedApplication] delegate] window] addSubview:bgView];
    bgView.frame = [[[UIApplication sharedApplication] delegate] window].bounds;
    // 嵌入view
    [bgView addSubview:view];
    
    [self popUpWithModel:model];
}

- (void)popUpWithView:(UIView *)view withToViewCtl:(nonnull UIViewController *)toCtl withAnimation:(QINAlertPopUpStyle)animation withCanTapBgCancel:(BOOL)canTapBgCancel closeBefore:(BeforeAlertBehavior)closeBefore {
    if (closeBefore == BeforeAlertBehaviorClose) {
        [self removePopUpView];
    } else if (closeBefore == BeforeAlertBehaviorHidden){
        [self hiddenCurrentPopUpView];
    }

    // 背景view
    QINPopAlertBgView *bgView = [[QINPopAlertBgView alloc] init];
    if (canTapBgCancel) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removePopUpViewWhenAppearOther)];
        tap.delegate = self;
        [bgView addGestureRecognizer:tap];
    }
    PopStyleModel *model = [[PopStyleModel alloc] init];
    model.appearWhenLastDismiss = YES;
    model.style = animation;
    model.popUpView = bgView;
    model.contentView = view;
    [self.maryStack addObject:model];
    
    [toCtl.view addSubview:bgView];
    bgView.backgroundColor = _bgColor ? _bgColor : [[UIColor blackColor] colorWithAlphaComponent:0.3];
    bgView.frame = toCtl.view.bounds;
    [toCtl.view addSubview:view];
    // 嵌入view
    [bgView addSubview:view];
    
    [self popUpWithModel:model];
}

- (void)removePopUpViewWhenAppearOther {
    [self removePopUpView];
    PopStyleModel *model = [self.maryStack lastObject];
    if (model.appearWhenLastDismiss == YES) {
        model.popUpView.hidden = NO;
    }
}

- (void)clear {
    [self.maryStack enumerateObjectsUsingBlock:^(PopStyleModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.popUpView.hidden = YES;
        [obj.popUpView removeFromSuperview];
    }];
    [self.maryStack removeAllObjects];
}

- (void)removePopUpView {
    PopStyleModel *model = [self.maryStack lastObject];
    [self.maryStack removeLastObject];
    [self dismissWithModel:model];
}

- (void)hiddenCurrentPopUpView {
    PopStyleModel *model = [self.maryStack lastObject];
    model.popUpView.hidden = YES;
}
- (void)showCurrentPopUpView {
    PopStyleModel *model = [self.maryStack lastObject];
    model.popUpView.hidden = NO;
}

- (void)popUpWithModel:(PopStyleModel *)model {
    if (model.style == QINAlertPopUpStyleCenter) {
        
        [model.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.width.mas_equalTo(model.contentView.bounds.size.width);
             make.height.mas_equalTo(model.contentView.bounds.size.height);
             make.center.mas_equalTo(model.popUpView);
         }];
        // 出场动画
        model.popUpView.alpha = 0;
        model.contentView.alpha = 0;
        model.contentView.transform = CGAffineTransformScale( model.popUpView.transform, 0.001, 0.001);
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            model.popUpView.alpha = 1;
            model.contentView.alpha = 1;
             model.contentView.transform = CGAffineTransformScale(model.contentView.transform, 1000, 1000);
         } completion:^(BOOL finished) {
             
         }];
    } else if (model.style == QINAlertPopUpStyleBottom) {
        
        [model.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(model.contentView.bounds.size.width);
            make.height.mas_equalTo(model.contentView.bounds.size.height);
            make.top.mas_equalTo(model.popUpView.mas_bottom);
            make.centerX.mas_equalTo(model.popUpView.mas_centerX);
        }];
        
        [model.popUpView.superview setNeedsUpdateConstraints];
        [model.popUpView setNeedsUpdateConstraints];
        [model.popUpView layoutIfNeeded];
        model.popUpView.alpha = 0;
        [UIView animateWithDuration:0.4 animations:^{
            model.popUpView.alpha = 1;
            [model.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(model.popUpView.mas_bottom).offset(-model.contentView.frame.size.height);
            }];
            [model.contentView.superview layoutIfNeeded];
        }] ;
    }
}

- (void)dismissWithModel:(PopStyleModel *)model {
    if (model.style == QINAlertPopUpStyleCenter) {
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            model.contentView.transform = CGAffineTransformScale(model.contentView.transform, 0.001, 0.001);
            model.popUpView.alpha = 0;
            model.contentView.alpha = 0;
        } completion:^(BOOL finished) {
            [model.popUpView removeFromSuperview];
        }];
    } else if (model.style == QINAlertPopUpStyleBottom) {
        [UIView animateWithDuration:0.4 animations:^{
            model.popUpView.alpha = 0;
            [model.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(model.popUpView.mas_bottom);
            }];
            [model.contentView.superview layoutIfNeeded];
        }] ;
    } else {
        [model.popUpView removeFromSuperview];
    }
}


// 存储视图
- (void)storeViewWithKey:(NSString *)key view:(id)view {
    if (SQ_Str_Not_Valid(key) || view == nil) {
        return;
    }
    [self removeViewWithKey:key];
    self.storeViewMap[key] = view;
}

// 删除视图
- (void)removeViewWithKey:(NSString *)key {
    id view = SQ_Dic_SafeGetValue(self.storeViewMap, key);
    if ([view isKindOfClass:[UIView class]]) {
        [((UIView *)view).layer removeAllAnimations];
        [view removeFromSuperview];
        [self.storeViewMap removeObjectForKey:key];
    }
//    else if ([view isKindOfClass:[ASDisplayNode class]]) {
//        [((ASDisplayNode *)view).layer removeAllAnimations];
//
//        [(ASDisplayNode *)view removeFromSupernode];
//        [self.storeViewMap removeObjectForKey:key];
//    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    PopStyleModel *model = [self.maryStack lastObject];
    if ([touch.view isKindOfClass:[model.popUpView class]]) {
        return YES;
    }
    return NO;
}

- (NSMutableArray *)maryStack {
    if (_maryStack == nil) {
        _maryStack = [[NSMutableArray alloc] init];
    }
    
    return _maryStack;
}

- (NSMutableDictionary *)storeViewMap {
    if (_storeViewMap == nil) {
        _storeViewMap = [NSMutableDictionary dictionary];
    }
    
    return _storeViewMap;
}




@end
